package content

import (
	"content_system/dao/def/content/model"
	"content_system/infra/db"
	"content_system/infra/id_gen"
	"context"
	"errors"
	"gorm.io/gorm"
	"sync"
)

var (
	contentDao     *ContentDao
	contentDaoOnce sync.Once
)

type ContentDao struct{}

func GetContentDao() *ContentDao {
	contentDaoOnce.Do(func() {
		contentDao = &ContentDao{}
	})
	return contentDao
}

func (c *ContentDao) Create(ctx context.Context, content *model.Content) error {
	table := db.ContentQuery.Content
	if content == nil {
		return errors.New("content is nil")
	}
	if content.ID == 0 {
		id, err := id_gen.Get()
		if err != nil {
			return err
		}
		content.ID = int64(id)
	}
	return table.WithContext(ctx).Create(content)
}

func (c *ContentDao) Update(ctx context.Context, contentID int64, updateFields map[string]interface{}) error {
	table := db.ContentQuery.Content
	_, err := table.WithContext(ctx).Where(table.ID.Eq(contentID)).Updates(updateFields)
	return err
}

func (c *ContentDao) GetByID(ctx context.Context, contentID int64) (*model.Content, error) {
	table := db.ContentQuery.Content
	r, err := table.WithContext(ctx).Where(table.ID.Eq(contentID)).First()
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return r, err
}

func (c *ContentDao) Delete(ctx context.Context, contentID int64) error {
	table := db.ContentQuery.Content
	_, err := table.WithContext(ctx).Where(table.ID.Eq(contentID)).Delete()
	return err
}
